﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Threading;
using A.HTMlServer;
namespace WF.Webdata
{
    public partial class Fashion : Form
    {
        #region 属性
        /// <summary>
        /// 分页
        /// </summary>
        public List<string> Plist=new List<string>();
        /// <summary>
        /// 内容
        /// </summary>
        public List<HListModel> Clist=new List<HListModel>();
        /// <summary>
        /// 采集源
        /// </summary>
        private List<HListModel> All =new List<HListModel>();

        private bool ActiveState = false;

        private bool ThreadState = false;

        private object objstate = new object();
        #endregion

        public Fashion()
        {
            InitializeComponent();
        }
        #region 事件
        private void button2_Click(object sender, EventArgs e)
        {
            new ArticleDownload().Show();
            this.Hide();
            //A.HTMlServer.Control.AddList(Clist);
        }
        private void button3_Click(object sender, EventArgs e)
        {
            ActiveState = true;
        }
        private void Binput_Click(object sender, EventArgs e)
        {
            //Clist.ForEach(new Action<string>(DatatoSql));
            Clist.ForEach(model => A.HTMlServer.ArticleData.DatatoSql(model));//效果和上面一样
            Binput.Enabled = false;
        }
        
        private void button1_Click(object sender, EventArgs e)
        {
            string strurl=textBox1.Text;
            //strurl = "http://lady.163.com/special/00263E71/shirt09.html";
            strurl = "http://lady.163.com/special/00263E71/majia09.html";

            Thread thread = new Thread(new ParameterizedThreadStart(GetPageHTML));
            //Thread thread = new Thread(new ParameterizedThreadStart(GetoneHTML));//单线程没有问题,多线程时应该是被重复的覆盖了
            thread.Start(strurl);

            //启动UI线程
            UIThread();
        }
        #endregion

        #region 线程
        private void UIThread()
        {
            Thread uithread = new Thread(new ThreadStart(this.Updatedata));
            uithread.Name = "UI";
            uithread.Start();
        }

        delegate void Dfun();
        private void Updatedata()
        {
            Dfun df=new Dfun(this.DataShow);
            do
            {
                this.Invoke(df);
                Thread.Sleep(500);
            } while (!ActiveState);
            //df = new Dfun(this.ShowBinput);
            df =()=>ShowBinput();//效果两同上
            this.Invoke(df);
        }

        private void ShowBinput()
        {
            Binput.Enabled = true;
        }

        /// <summary>
        /// 显示在列表中
        /// </summary>
        private void DataShow()
        {
            lock(objstate)
            {
                if (Clist.Count > cBox1.Items.Count)
                {
                    for (var i = cBox1.Items.Count; i <Clist.Count;i++ )
                    {
                        cBox1.Items.Add(i+"["+Clist[i].Url+"]");
                    }
                }
            }
        }
        #endregion

        #region HTML分析
        private void GetHtml()
        {
            //增加本页
            //Plist.Add(obj.ToString());

            for (var i = 0; i < 5;i++)
            {
                Thread thread = new Thread(ThreadURL);
                thread.Name = "T"+i.ToString();
                thread.Start();
            }
        }

        private void ThreadURL()
        {
            HListModel model = null;
            do
            {
                lock (objstate)
                {
                    if (All.Count > 0)
                    {
                        model = All[0];
                        All.RemoveAt(0);
                    }
                    else { model = null; }
                }

                if (model != null)
                {
                    GetURL(model);
                }
                
            }while(!ActiveState);
        }

        private void GetURL(HListModel model)
        {
            Plist.Add(model.Url);
            DCommon dc = new DCommon();
            string Html = dc.GetStrHtml(model.Url);
            Html = GetMainHtml(Html);
            if (Html == "")
            {
                return;
            }
            Regex r = new Regex(@"http://lady.163.com/.*?\.html", RegexOptions.IgnoreCase);
            MatchCollection MC = r.Matches(Html);
            if (MC.Count > 0)
            {
                HListModel HM;
                string page = model.Url.Substring(model.Url.LastIndexOf("/") + 1, (model.Url.LastIndexOf(".") - model.Url.LastIndexOf("/") - 1));
                if (page.Contains("_"))
                {
                    page = page.Substring(0, page.LastIndexOf("_"));
                }
                foreach (Match m in MC)
                {
                    if (m.Value.Contains(page))
                    {
                        if (!Plist.Contains(m.Value))
                        {
                            HM = new HListModel();
                            HM = model;
                            HM.Url = m.Value;
                            //model.Url = m.Value;
                            GetURL(HM);
                        }
                    }
                    else if ((Clist.Count == 0 || Clist.TrueForAll((hm) => {return hm.Url != m.Value; })))
                    {
                        HM = new HListModel();
                        HM.Other = page;
                        HM.Name = model.Url;
                        HM.Code = model.Code;
                        HM.Url = m.Value;
                        Clist.Add(HM);
                    }
                    Thread.Sleep(200);
                }
            }
        }

        /// <summary>
        /// 获取HTML的主要部分
        /// </summary>
        /// <param name="Html">HTML</param>
        /// <returns>MainHTMl</returns>
        private string GetMainHtml(string Html)
        {
            if (Html != null)
            {
                Regex r = new Regex("<div class=\"piclist120-160\">.*?<span class=\"line\"></span>", RegexOptions.Singleline);
                Match m = r.Match(Html);
                if (m.Success)
                {
                    return m.Value;
                }
            }
            return "";
        }

        /// <summary>
        /// 获取所有采集URL
        /// </summary>
        /// <param name="Html">HTML</param>
        /// <returns>MainHTMl</returns>
        private string GetALLURL(string Html)
        {
            if (Html != null)
            {
                Regex r = new Regex("<div class=\"area\">.*?<dt>人物库</dt>", RegexOptions.Singleline);
                Match m = r.Match(Html);
                if (m.Success)
                {
                    return m.Value;
                }
            }
            return "";
        }

        /// <summary>
        /// 测试一个网址的运行过程
        /// </summary>
        /// <param name="o">string</param>
        private void GetoneHTML(object o)
        {
            HListModel model=null;
            model = new HListModel();
            model.Url = "http://lady.163.com/special/00263E71/casualwear09.html";
            model.Code ="休闲运动";
            GetURL(model);
        }


        private void GetPageHTML(object o)
        {
            HListModel model=null;
            DCommon dc = new DCommon();
            string Html = dc.GetStrHtml(o.ToString());
            Html = GetALLURL(Html);
            Regex r = new Regex(@"<li>.*</li>", RegexOptions.IgnoreCase);
            MatchCollection MC = r.Matches(Html);
            foreach (Match m in MC)
            {
                model = new HListModel();
                Regex r1 = new Regex(@"http://lady.163.com/.*?\.html", RegexOptions.IgnoreCase);
                model.Url = r1.Match(m.Value).Success ? r1.Match(m.Value).Value : "";
                Regex r2 = new Regex(@"[\u4e00-\u9fa5]+", RegexOptions.IgnoreCase);
                model.Code = r2.Match(m.Value).Success ? r2.Match(m.Value).Value : "";
                lock (objstate)
                {
                    All.Add(model);
                }
                if (!ThreadState&&All.Count != 0)
                {
                    GetHtml();
                    //All.ForEach((A) => GetURL(A));
                    //GetURL(All[0]);
                }
                Thread.Sleep(500);
            }
            int i=0;
            do
            {
                i=Clist.Count;
                Thread.Sleep(1000);
            }while(i!=Clist.Count);
            if (Plist != null && Clist != null)
            {
                //保存所有的分页
                MessageBox.Show("Plist:" + Plist.Count + "  Clist:" + Clist.Count);
                OneClist();
            }
        }

        private void OneClist()
        {
            Clist.RemoveAll((C) => { return C.Url.Contains("special"); });
        }
        #endregion
    }
}
